package org.KeyCrafter.util;

import java.nio.charset.StandardCharsets;

// Redis 协议
public class CodecUtil {
    // 简单字符串
    private static final char SIMPLE_STRING = '+';
    // 批量字符串
    private static final char BULK_STRING = '$';
    // 错误
    private static final char ERROR = '-';
    // 整数
    private static final char INTEGER = ':';
    // 数组
    private static final char ARRAY = '*';
    // Redis协议的命令和回复之间使用回车换行符（\r\n）进行分隔
    private static final String CTRL = "\r\n";

    //public static StringBuilder builder = new StringBuilder(1024);

    public static String encodeSimpleString(String content) {
        return SIMPLE_STRING +
                content +
                CTRL;
    }

    public static String encodeBulkString(String content) {
        StringBuilder builder = new StringBuilder();
        byte[] bytes = content.getBytes(StandardCharsets.UTF_8);
        builder.append(BULK_STRING)
                .append(bytes.length)
                .append(CTRL)
                .append(content)
                .append(CTRL);
        return builder.toString();
    }

    // 编码数组
    public static String encodeArray(String[] contents) {
        StringBuilder builder = new StringBuilder();
        builder.append(contents.length)
                .append(CTRL);
        for (String s : contents) {
            builder.append(encodeBulkString(s));
        }
        return builder.toString();
    }

    // 编码数组 闭区间
    public static String encodeArray(String[] contents, int start, int end) {
        StringBuilder builder = new StringBuilder();
        builder.append(end - start + 1)
                .append(CTRL);
        for (int i = start; i <= end; i++) {
            builder.append(contents[i]);
        }
        return builder.toString();
    }
}
